package com.codi.api.controller.organ;

import com.codi.api.security.UserUtil;
import com.codi.base.log.annotation.Loggable;
import com.codi.bus.constant.GlobalConstant;
import com.codi.bus.core.dao.OrganAgentDao;
import com.codi.bus.core.domain.OrganAgent;
import com.codi.bus.core.domain.OrganProfile;
import com.codi.bus.core.domain.TradeNotice;
import com.codi.bus.core.domain.User;
import com.codi.bus.core.resultModel.BaseListResult;
import com.codi.bus.core.resultModel.BaseResult;
import com.codi.bus.core.resultModel.ValidateTokenResult;
import com.codi.bus.core.service.*;
import com.codi.bus.core.service.organ.OrganMineService;
import com.codi.bus.core.service.organ.OrganProfileService;
import com.codi.bus.exception.BaseException;
import com.codi.message.util.MessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lvgo
 * @version 1.0
 * @Description: 机构相关
 * @date 2018/5/8 13:33
 */
@RestController
@RequestMapping("/organ")
@Slf4j
public class OrganMineController {

    @Resource
    private OrganMineService organMineService;
    @Autowired
    private OrganProfileService organProfileService;
    @Autowired
    private LookupService lookupService;
    @Resource
    private OrganAgentDao organAgentDao;
    @Autowired
    private UserService userService;
    @Resource(name = "fundDetailService")
    private FundDetailService fundDetailService;
    @Resource(name = "fundInfoService")
    private FundInfoService fundInfoService;
    @Autowired
    private T0Service t0Service;





    /**
     * 切换账号
     */
    @Loggable
    @GetMapping("/listOrgAccounts")
    public BaseResult listOrgAccounts(HttpServletRequest request) {
        String token = request.getHeader(GlobalConstant.HEADER_AUTH_TOKEN);
        String deviceId = request.getHeader(GlobalConstant.HEADER_APP_DEVICE);
        ValidateTokenResult validateTokenResult = userService.validateToken(token, deviceId);
        Long userId = validateTokenResult.getUserId();
        BaseResult result = new BaseResult();

        User user = userService.getUser(userId);

        String mobile = user.getUserMobile();

        OrganAgent organAgent = organAgentDao.getEntityByMobile(mobile.trim());

        List<OrganProfile> organProfilesA = new ArrayList<>();

        if (organAgent != null) {
            Long agentId = organAgent.getAgentId();
            List<OrganProfile> temp = organProfileService.queryListByAgentId(agentId);
            //作为经办人登录
            for (OrganProfile organProfile : temp) {
                if (organProfile.getState() != GlobalConstant.ORGAN_STATE_PASS) {
                    continue;
                }
                organProfile.setIsAgent(true);
                organProfilesA.add(organProfile);
            }
        }


        //作为管理人登录
        List<OrganProfile> organProfilesB = organProfileService.queryListByUserId(userId);

        for (OrganProfile organProfile : organProfilesB) {
            organProfile.setIsAgent(false);
        }

        organProfilesA.addAll(organProfilesB);

        Map<Long, OrganProfile> map = new HashMap<>();

        for (OrganProfile organProfile : organProfilesA) {
            map.put(organProfile.getProfileId(), organProfile);
        }

        List<OrganProfile> organProfilesReal = new ArrayList<>();

        for (Long profileId : map.keySet()) {
            organProfilesReal.add(map.get(profileId));
        }


        result.setResult(organProfilesReal);

        return result;

    }


    /**
     * 获取经办人
     *
     * @param profileId 企业id
     */
    @Loggable
    @GetMapping("/mine/getAgent")
    public BaseResult getAgent(String profileId) {
        BaseResult baseResult = new BaseResult();
        try {

            OrganAgent organAgent = organMineService.getAgent(profileId);
            baseResult.setResult(organAgent);
        } catch (BaseException e) {
            baseResult.setSuccess(false);
            baseResult.setErrorCode(e.getCode());
            baseResult.setErrorMessage(MessageUtil.getErrorMsg(e.getCode()));
            e.printStackTrace();
        }
        return baseResult;
    }

    /**
     * 添加交易报备号
     *
     * @param profileId   企业id
     * @param noticePhone 电话
     * @param noticeName  名称
     */
    @Loggable
    @PostMapping("/mine/addTradeNotice")
    public BaseResult addTradeNotice(String profileId, String noticePhone, String noticeName) {
        BaseResult baseResult = new BaseResult();
        try {
            String userId = UserUtil.getLoginUserId().toString();
            TradeNotice tradeNotice = organMineService.saveTradeNotice(userId, profileId, noticePhone, noticeName);
            baseResult.setResult(tradeNotice);
            log.info("添加交易报备号成功。");
        } catch (BaseException e) {
            log.error("添加交易报备号失败，错误信息：{}", e.getMessage());
            baseResult.setSuccess(false);
            baseResult.setErrorCode(e.getCode());
            baseResult.setErrorMessage(MessageUtil.getErrorMsg(e.getCode()));
            e.printStackTrace();
        }
        return baseResult;
    }


    /**
     * 删除交易报备号
     *
     * @param tradeNoticeId 交易报备号id
     */
    @Loggable
    @GetMapping("/mine/deleteTradeNotice")
    public BaseResult deleteTradeNotice(String tradeNoticeId) {
        BaseResult baseResult = new BaseResult();
        try {
            organMineService.deleteTradeNotice(tradeNoticeId);
            log.info("删除交易报备号成功。");
        } catch (BaseException e) {
            baseResult.setSuccess(false);
            baseResult.setErrorCode(e.getCode());
            baseResult.setErrorMessage(MessageUtil.getErrorMsg(e.getCode()));
            e.printStackTrace();
        }
        return baseResult;
    }

    /**
     * 交易报备号列表
     *
     * @param profileId 企业id
     */
    @Loggable
    @GetMapping("/mine/tradeNoticeList")
    public BaseListResult tradeNoticeList(String profileId) {
        BaseListResult baseResult = new BaseListResult();
        try {
            List<TradeNotice> tradeNotices = organMineService.selectTradeNoticeList(profileId);
            baseResult.setTotalCount((long) tradeNotices.size());
            baseResult.setResult(tradeNotices);
        } catch (BaseException e) {
            baseResult.setSuccess(false);
            baseResult.setErrorCode(e.getCode());
            baseResult.setErrorMessage(MessageUtil.getErrorMsg(e.getCode()));
            e.printStackTrace();
        }
        return baseResult;
    }

}
